package com.campus.client.view;

import com.campus.client.controller.LibraryController;
import com.campus.client.net.ClientConnector;
import com.campus.common.vo.Book;
import com.campus.common.vo.BorrowRecord;
import com.campus.common.vo.User;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class LibraryFrame {
    private LibraryController libraryController;
    private GridPane bookGrid;
    private ScrollPane scrollPane;
    private MenuBar menuBar;
    private final int COLS = 2; // 每行2个书籍
    private Button backButton;
    private List<Book> currentBooks;
    private User user = new User();

    public User getUser() { return user; }

    public void setUser(String Id, String password, String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
    }

    public void start(Stage primaryStage) throws Exception {
        // 初始化 LibraryController
        libraryController = new LibraryController(new ClientConnector("172.20.10.2", 8888));

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        // 顶部标题栏
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));

        Label titleLabel = new Label("校园图书馆");
        titleLabel.getStyleClass().add("header-title");

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 创建菜单栏和借阅列表按钮
        menuBar = createMenuBar();
        backButton = createStyledButton("返回");
        backButton.getStyleClass().add("secondary-button");
        backButton.setOnAction(e -> {
            try {
                back();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        Region buttonSpacer = new Region();
        buttonSpacer.setPrefWidth(10);

        Button borrowListButton = createStyledButton("查看借阅列表");
        borrowListButton.getStyleClass().add("primary-button");
        borrowListButton.setOnAction(e -> showBorrowList());

        headerBox.getChildren().addAll(titleLabel, spacer, menuBar, borrowListButton, buttonSpacer, backButton);
        root.setTop(headerBox);

        // 内容区域
        VBox contentBox = new VBox();
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));

        // 添加搜索面板
        HBox searchPanel = createSearchPanel();
        contentBox.getChildren().add(searchPanel);

        // 书籍网格显示区域
        bookGrid = new GridPane();
        bookGrid.setHgap(20);
        bookGrid.setVgap(20);
        bookGrid.setPadding(new Insets(10));
        bookGrid.setAlignment(Pos.TOP_CENTER);

        // 设置列约束，使两列等宽
        ColumnConstraints col1 = new ColumnConstraints();
        col1.setPercentWidth(50);
        ColumnConstraints col2 = new ColumnConstraints();
        col2.setPercentWidth(50);
        bookGrid.getColumnConstraints().addAll(col1, col2);

        scrollPane = new ScrollPane(bookGrid);
        scrollPane.getStyleClass().add("scroll-pane");
        scrollPane.setFitToWidth(true);

        contentBox.getChildren().add(scrollPane);
        root.setCenter(contentBox);

        // 默认加载所有书籍
        loadAllBooks();

        Scene scene = new Scene(root, 1000, 600);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        primaryStage.setTitle("校园图书馆 - 学生版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // 创建菜单栏
    private MenuBar createMenuBar() {
        MenuBar menuBar = new MenuBar();
        menuBar.getStyleClass().add("library-menu-bar");

        Menu allBooksMenu = new Menu("操作");
        MenuItem allBooksItem = new MenuItem("显示所有书籍");
        allBooksItem.setOnAction(e -> loadAllBooks());

        MenuItem sortByTitleItem = new MenuItem("按书名排序");
        sortByTitleItem.setOnAction(e -> sortBooksByTitle());

        MenuItem sortByAuthorItem = new MenuItem("按作者排序");
        sortByAuthorItem.setOnAction(e -> sortBooksByAuthor());

        MenuItem filterAvailableItem = new MenuItem("筛选可借阅");
        filterAvailableItem.setOnAction(e -> filterAvailableBooks());

        allBooksMenu.getItems().addAll(allBooksItem, sortByTitleItem, sortByAuthorItem, filterAvailableItem);

        menuBar.getMenus().add(allBooksMenu);
        return menuBar;
    }

    // 创建搜索面板
    private HBox createSearchPanel() {
        HBox searchPanel = new HBox(10);
        searchPanel.setPadding(new Insets(10));
        searchPanel.setAlignment(Pos.CENTER_LEFT);
        searchPanel.getStyleClass().add("search-panel");
        TextField searchField = new TextField();
        searchField.setPromptText("输入书名或作者");
        searchField.setPrefWidth(200);

        // 新增类别下拉框
        ComboBox<String> categoryComboBox = new ComboBox<>();
        categoryComboBox.setPromptText("选择书籍类别");
        categoryComboBox.setPrefWidth(150);

        // 从服务器获取类别列表
        try {
            List<String> categories = libraryController.getAllCategories();
            categoryComboBox.getItems().addAll(categories);
        } catch (Exception ex) {
            ex.printStackTrace();
            showAlert("错误", "获取类别列表失败: " + ex.getMessage(), Alert.AlertType.ERROR);
        }

        Button searchButton = createStyledButton("搜索");
        searchButton.setOnAction(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                try {
                    List<Book> booksByTitle = libraryController.searchBooksByTitle(keyword);
                    List<Book> booksByAuthor = libraryController.searchBooksByAuthor(keyword);

                    // 合并结果，去重
                    Set<Book> resultSet = new HashSet<>();
                    resultSet.addAll(booksByTitle);
                    resultSet.addAll(booksByAuthor);

                    displaySearchResults(new ArrayList<>(resultSet), keyword);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    showAlert("错误", "搜索失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                }
            }
        });

        // 新增筛选按钮
        Button filterButton = createStyledButton("筛选");
        filterButton.setOnAction(e -> {
            String selectedCategory = categoryComboBox.getValue();
            if (selectedCategory != null && !selectedCategory.isEmpty()) {
                try {
                    List<Book> booksByCategory = libraryController.searchBooksByCategory(selectedCategory);
                    displaySearchResults(booksByCategory, "类别: " + selectedCategory);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    showAlert("错误", "筛选失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                }
            } else {
                showAlert("提示", "请选择书籍类别", Alert.AlertType.INFORMATION);
            }
        });

        Button clearButton = createStyledButton("清除搜索");
        clearButton.setOnAction(e -> {
            searchField.clear();
            categoryComboBox.getSelectionModel().clearSelection();
            loadAllBooks();
        });

        searchPanel.getChildren().addAll(
                new Label("🔍按书名/作者搜索:"), searchField, searchButton,
                new Label("🔍按类别筛选:"), categoryComboBox, filterButton, clearButton
        );

        return searchPanel;
    }

    // 加载所有书籍
    private void loadAllBooks() {
        bookGrid.getChildren().clear();
        try {
            currentBooks = libraryController.getBooks();
            displayBooks(currentBooks, "所有书籍");
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载书籍失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }
    private void displayBooks(List<Book> books, String title) {
        bookGrid.getChildren().clear();

        Label titleLabel = new Label(title);
        titleLabel.getStyleClass().add("category-title");
        bookGrid.add(titleLabel, 0, 0, COLS, 1);

        if (books.isEmpty()) {
            Label noResultLabel = new Label("没有找到相关书籍");
            noResultLabel.getStyleClass().add("empty-label");
            bookGrid.add(noResultLabel, 0, 1, COLS, 1);
        } else {
            for (int i = 0; i < books.size(); i++) {
                Book book = books.get(i);
                VBox bookCard = createBookCard(book);
                int col = i % COLS;
                int row = (i / COLS) + 1;
                bookGrid.add(bookCard, col, row);
            }
        }
    }

    // 添加排序和筛选方法
    private void sortBooksByTitle() {
        if (currentBooks == null || currentBooks.isEmpty()) return;

        currentBooks.sort((b1, b2) -> {
            // 使用Collator进行中文拼音排序
            java.text.Collator collator = java.text.Collator.getInstance(java.util.Locale.CHINA);
            return collator.compare(b1.getTitle(), b2.getTitle());
        });

        displayBooks(currentBooks, "按书名排序");
    }

    private void sortBooksByAuthor() {
        if (currentBooks == null || currentBooks.isEmpty()) return;

        currentBooks.sort((b1, b2) -> {
            // 使用Collator进行中文拼音排序
            java.text.Collator collator = java.text.Collator.getInstance(java.util.Locale.CHINA);
            return collator.compare(b1.getAuthor(), b2.getAuthor());
        });

        displayBooks(currentBooks, "按作者排序");
    }

    private void filterAvailableBooks() {
        if (currentBooks == null || currentBooks.isEmpty()) return;

        List<Book> availableBooks = new ArrayList<>();
        for (Book book : currentBooks) {
            if (book.isAvailable() && book.getStock() > 0) {
                availableBooks.add(book);
            }
        }

        displayBooks(availableBooks, "可借阅书籍");
    }
    // 创建书籍卡片
    private VBox createBookCard(Book book) {
        VBox card = new VBox(10);
        card.setPadding(new Insets(15));
        card.getStyleClass().add("book-card");
        card.setMaxWidth(350);
        card.setMinWidth(350);

        // 书籍信息
        Label titleLabel = new Label(book.getTitle().trim());
        titleLabel.getStyleClass().add("book-title");
        titleLabel.setWrapText(true);

        Label authorLabel = new Label("作者: " + book.getAuthor().trim());
        authorLabel.getStyleClass().add("book-author");

        Label availableLabel = new Label("可借状态: " + (book.isAvailable() ? "可借" : "不可借"));
        availableLabel.getStyleClass().add(book.isAvailable() ? "book-available" : "book-unavailable");

        Label stockLabel = new Label("库存: " + book.getStock());
        stockLabel.getStyleClass().add("book-stock");


        Label timeLimitLabel = new Label("可借时长: " + book.getTimeLimit() + "天");
        timeLimitLabel.getStyleClass().add("book-time-limit");

        // 底部按钮区域
        HBox buttonBox = new HBox();
        buttonBox.setAlignment(Pos.CENTER_RIGHT);

        // 借书按钮
        Button borrowButton = createStyledButton("借书");
        borrowButton.getStyleClass().add("primary-button");
        borrowButton.setDisable(!book.isAvailable());
        borrowButton.setOnAction(e -> {
            try {
                String result = libraryController.borrowBook(book.getId(), user.getId());
                if (result.contains("成功")) {
                    showAlert("成功", result, Alert.AlertType.INFORMATION);
                    loadAllBooks();
                } else {
                    showAlert("失败", result, Alert.AlertType.ERROR);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("错误", "借书失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        buttonBox.getChildren().addAll(spacer, borrowButton);

        card.getChildren().addAll(titleLabel, authorLabel, availableLabel, stockLabel, timeLimitLabel, buttonBox);
        return card;
    }

    // 显示搜索结果
    private void displaySearchResults(List<Book> books, String keyword) {
        currentBooks = books;
        displayBooks(books, "搜索包含 '" + keyword + "' 的结果 (" + books.size() + " 本)");
    }

    // 显示借阅列表
    // 显示借阅列表
    private void showBorrowList() {
        System.out.println("DEBUG: 开始显示借阅列表，用户ID: " + user.getId());

        Stage borrowStage = new Stage();
        borrowStage.setTitle("我的借阅列表");

        BorderPane root = new BorderPane();
        root.setPadding(new Insets(15));
        root.getStyleClass().add("dialog-container");

        Label titleLabel = new Label("我的借阅列表");
        titleLabel.getStyleClass().add("dialog-title");
        BorderPane.setAlignment(titleLabel, Pos.CENTER);
        root.setTop(titleLabel);

        VBox borrowContent = new VBox(10);
        borrowContent.setPadding(new Insets(15));

        try {
            // 从服务器获取当前用户的借阅记录
            System.out.println("DEBUG: 正在获取用户借阅记录...");
            List<BorrowRecord> borrowRecords = libraryController.getUserBorrowRecords(user.getId());

            // 添加调试信息
            System.out.println("DEBUG: 获取到的借阅记录: " + (borrowRecords != null ? borrowRecords.size() + " 条" : "null"));

            if (borrowRecords == null) {
                System.out.println("DEBUG: 借阅记录为null，初始化为空列表");
                borrowRecords = new ArrayList<>(); // 防止null
            }

            if (borrowRecords.isEmpty()) {
                System.out.println("DEBUG: 借阅列表为空");
                Label emptyLabel = new Label("借阅列表为空");
                emptyLabel.getStyleClass().add("empty-label");
                borrowContent.getChildren().add(emptyLabel);
            } else {
                System.out.println("DEBUG: 开始显示 " + borrowRecords.size() + " 条借阅记录");
                for (BorrowRecord record : borrowRecords) {
                    System.out.println("DEBUG: 处理借阅记录 - 书籍ID: " + record.getBookId() + ", 书名: " + record.getBookTitle());

                    HBox itemRow = new HBox(15);
                    itemRow.setPadding(new Insets(10));
                    itemRow.getStyleClass().add("borrow-item");
                    itemRow.setAlignment(Pos.CENTER_LEFT);

                    // 书籍信息和借阅日期
                    VBox infoBox = new VBox(5);
                    Label titleLabel2 = new Label(record.getBookTitle().trim());
                    titleLabel2.getStyleClass().add("book-title");

                    Label authorLabel = new Label("作者: " + record.getBookAuthor().trim());
                    authorLabel.getStyleClass().add("book-author");

                    // 添加借阅日期和归还期限显示
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Label borrowDateLabel = new Label("借阅日期: " + dateFormat.format(record.getBorrowDate()));
                    borrowDateLabel.getStyleClass().add("borrow-date");

                    Label dueDateLabel = new Label("归还期限: " + dateFormat.format(record.getDueDate()));
                    dueDateLabel.getStyleClass().add("due-date");
                    boolean isOverdue = new Date().after(record.getDueDate());
                    Label statusLabel = new Label("状态: " + (isOverdue ? "超时" : "未超时"));
                    statusLabel.getStyleClass().add(isOverdue ? "overdue-status" : "normal-status");
                    infoBox.getChildren().addAll(titleLabel2, authorLabel, borrowDateLabel, dueDateLabel,statusLabel);

                    // 还书按钮
                    Button returnButton = createStyledButton("还书");
                    returnButton.getStyleClass().add("primary-button");
                    returnButton.setOnAction(e -> {
                        try {
                            System.out.println("DEBUG: 尝试还书 - 书籍ID: " + record.getBookId() + ", 用户ID: " + user.getId());
                            String result = libraryController.returnBook(record.getBookId(), user.getId());
                            System.out.println("DEBUG: 还书结果: " + result);

                            if (result.contains("成功")) {
                                showAlert("成功", result, Alert.AlertType.INFORMATION);
                                // 刷新借阅列表
                                refreshBorrowView(borrowStage);
                                // 刷新主界面
                                loadAllBooks();
                            } else {
                                showAlert("失败", result, Alert.AlertType.ERROR);
                            }
                        } catch (Exception ex) {
                            System.out.println("DEBUG: 还书异常: " + ex.getMessage());
                            ex.printStackTrace();
                            showAlert("错误", "还书失败: " + ex.getMessage(), Alert.AlertType.ERROR);
                        }
                    });

                    itemRow.getChildren().addAll(infoBox, returnButton);
                    borrowContent.getChildren().add(itemRow);
                }
            }
        } catch (Exception e) {
            System.out.println("DEBUG: 获取借阅列表异常: " + e.getMessage());
            e.printStackTrace();
            showAlert("错误", "获取借阅列表失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }

        ScrollPane scrollPane = new ScrollPane(borrowContent);
        scrollPane.getStyleClass().add("scroll-pane");
        root.setCenter(scrollPane);

        Scene scene = new Scene(root, 600, 400);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        borrowStage.setScene(scene);
        borrowStage.show();
        System.out.println("DEBUG: 借阅列表窗口已显示");
    }

    // 刷新借阅列表视图
    private void refreshBorrowView(Stage borrowStage) {
        borrowStage.close();
        showBorrowList();
    }

    // 统一按钮创建方法
    private Button createStyledButton(String text) {
        Button button = new Button(text);
        button.getStyleClass().add("styled-button");
        return button;
    }

    // 统一提示对话框
    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type, message, ButtonType.OK);
        alert.setHeaderText(title);
        alert.showAndWait();
    }

    public void back() throws IOException {
        // 获取当前登录窗口的Stage
        Stage passwordChangeStage = (Stage) backButton.getScene().getWindow();

        if(user.getRole().equals("教师")){
            TeacherMainFrame teacherMainFrame = new TeacherMainFrame();
            teacherMainFrame.setUser(user.getId(),user.getPassword(),user.getRole());
            Stage stage = new Stage();
            teacherMainFrame.show(stage);
        }else{
            StudentMainFrame studentMainFrame = new StudentMainFrame();
            studentMainFrame.setUser(user.getId(),user.getPassword(),user.getRole());
            Stage stage = new Stage();
            studentMainFrame.show(stage);
        }

        passwordChangeStage.close();
    }
}